import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入vuex数据
import store from '@/store/index.js'

// 导入组件
import Login from '../views/login/login.vue'
import Main from '../views/main/main.vue'
import Home from '../views/Home/Home.vue'
import User from '../views/User/User.vue'
import Search from '@/views/search/search.vue'
import searchResult from '@/views/searchResult/searchResult.vue'
import ArticleDetail from '@/views/ArticleDetail/ArticleDetail.vue'
import userEdit from '@/views/userEdit/userEdit.vue'
import Chat from '@/views/chat/chat.vue'

Vue.use(VueRouter)

// 固定代码
// 1. 将 VueRouter 本身提供的 $router.push 方法转存到常量中
const originalPush = VueRouter.prototype.push
// 2. 自定义 $router.push 方法，在内部调用原生的 originalPush 方法进行路由跳转；并通过 .catch 捕获错误
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  // 通过 .catch 捕获错误
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/login',
    component: Login,
    name: 'login'
  },
  {
    path: '/',
    component: Main,
    children: [{
      path: '',
      component: Home,
      name: 'home',
      meta: {
        top: 0,
        isRecordTop: true
      }
    }, {
      path: '/user',
      component: User,
      name: 'user'
    }]
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/:kw',
    component: searchResult,
    name: 'search-result',
    props: true
  },
  {
    path: '/article/:id',
    component: ArticleDetail,
    name: 'art-detail',
    props: true

  },
  {
    path: '/user/edit',
    component: userEdit,
    name: 'user-edit'
  },
  {
    path: '/chat',
    component: Chat,
    name: 'chat'
  }
]

const router = new VueRouter({
  routes
})

// 定义一个数组，把访问时需要权限的路径放在该数组中
const pathArr = ['/user', '/user/edit']
// 设置一个全局守卫，
router.beforeEach((to, from, next) => {
  if (from.meta.isRecordTop) {
    from.meta.top = window.scrollY
  }
  // 判断，将要访问的路由对象是否在需要权限的数组范围之内，使用indexof，返回-1表示未找到，取反表示存在
  if (pathArr.indexOf(to.path) !== -1) {
    // 判断，是否已经登录
    const tokenStr = store.state.tokenInfo.token
    if (tokenStr) {
      next()
    } else {
      // to表示访问未遂的路由对象
      next(`/login?pre=/${to.fullPath}`)
    }
  } else {
    next()
  }
})

export default router
